<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/26 0026
 * Time: 17:31
 */
namespace app\manager\model;


use app\common\helper\Obj2Array;
use app\common\model\Model;
use think\Db;
use think\Exception;

class ManagerRoleModel extends Model {
    public $error_msg;

    /**
     * 获取说有的角色以及将标识已经获得的角色到数组
     *
     * @param $manager_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function roleList($manager_id) {
        $roleM = new RoleModel();
        $role = $roleM->field(['id', 'name'])->where(['status' => RoleModel::STATUS_OK])->select();
        if (!empty($role)) {
            $role = Obj2Array::resObject2Array($role);
        }

        $has = $this->where(['manager_id' => $manager_id])->column('role_id');
        $role_list = $this->format($role, $has);
        return $role_list;
    }

    /**
     * @param $role
     * @param $has
     * @return array
     */
    private function format($role, $has) {
        $role_list = [];
        foreach ($role as $item) {
            if (in_array($item['id'], $has)) {
                $item['had'] = 1;
            } else {
                $item['had'] = 0;
            }
            $role_list[] = $item;
        }
        return $role_list;
    }

    /**
     * 分配角色
     *
     * @param $data
     * @return bool
     */
    public function dispatch($data) {
        $manager_id = $data['manager_id'];
        $role_list = $data['role_list'];
        $insert_data = $this->insertFormat($manager_id, $role_list);
        Db::startTrans();
        try {
            // 删除原有
            $this->where(['manager_id' => $manager_id])->delete();
            // 批量插入
            if (!$this->insertAll($insert_data)) {
                throw new Exception('角色入库失败');
            }
            Db::commit();
        }catch (\Exception $e) {
            $this->error_msg = $e->getMessage();
            Db::rollback();
            return false;
        }
        return true;
    }

    private function insertFormat($manager_id, $role_list) {
        $list = [];
        foreach ($role_list as $key => $li) {
            $list[$key]['role_id'] = $li;
            $list[$key]['manager_id'] = $manager_id;
        }
        return $list;
    }
}